/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.emocbc.cbcdb.dao;

import com.elcom.util.DBUtil;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;

/**
 *
 * @author GiangLT
 */
public abstract class BaseDao<T> implements Serializable {

//    protected final DbAccess dbAccess = DbAccess.getInstance();
    protected final String JNDI = "jdbc/cbcdb";
    
    public int insert(T record) throws SQLException {
        Connection con = DBUtil.getConnection(JNDI);
        Statement st = null;
        try {
            DSLContext context = DSL.using(con, SQLDialect.MYSQL);
            String sql = getInsertSql(record, context);
            st = con.createStatement();
            return st.executeUpdate(sql);
        } finally {
            DbAccess.closeStatement(st);
            DbAccess.closeConnection(con);
        }
    }

    public void batchInsert(List<T> records) throws SQLException {
        Connection con = DBUtil.getConnection(JNDI);
        Statement st = null;
        try {
            st = con.createStatement();
            for (T record : records) {
                DSLContext context = DSL.using(con, SQLDialect.MYSQL);
                st.addBatch(getInsertSql(record, context));
            }
            st.executeBatch();
        } finally {
            DbAccess.closeStatement(st);
            DbAccess.closeConnection(con);
        }
    }
    
    protected abstract String getInsertSql(T record, DSLContext context) throws SQLException;
}
